<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" custom-class="mydialog" width="900px"
    title="新建月度盘点" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="110px" size="small">
      <el-row gutter="40">
        <el-col :span="12">
          <el-form-item label="配送商名称" prop="distributeName">
            <el-autocomplete v-model="openForm.distributeName" style="width: 100%" placeholder="请选择配送商" ref="autocomplete"
              :fetch-suggestions="querySearchAsync" placement="bottom" @select="handleSelect" clearable @clear="handleClear">
              <template #default="{ item }">
                {{ item.distributeName }}
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="盘点时间" prop="checkTime">
            <date-picker v-model:date="openForm.checkTime" type="date" placeholder="选择盘点时间" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <item-title title="盘点产品明细">
            <template #btn>
              <el-button class="border-btn" size="mini" @click="handlAdd(null)">添加</el-button>
              <el-button class="border-btn" size="mini" @click="handlDelete(null,1)">全部删除</el-button>
            </template>
          </item-title>
        </el-col>

        <el-col :span="24">
          <el-form-item prop="tableData" label-width="0">
            <table-view :data="openForm.tableData" class="tableForm" header-cell-class-name="table-header" size="medium"
              border>

              <el-table-column type="index" label="序号" align="center" width="50" />

              <el-table-column label="产品通用名" align="center" :show-overflow-tooltip="true">
                <template #default="scope">
                  <el-form-item label-width="0" :prop="'tableData.' + scope.$index + '.productId'"
                    :rules="{ required: true, message: '请选择产品通用名', trigger: 'change'}">
                    <el-select v-model="scope.row.productId" style="width: 100%" placeholder="请选择产品通用名"
                      @change="()=>handlRddtype(scope.row.productId, scope.$index)">
                      <el-option v-for="item in productList" :key="item.id" :label="getProductName(item)"
                        :value="item.id" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="商品名" prop="product.productName" align="center" :show-overflow-tooltip="true" />

              <el-table-column label="生产厂家" prop="product.producer" align="center" :show-overflow-tooltip="true" />

              <el-table-column label="包装规格" prop="product.packSpecs" align="center" :show-overflow-tooltip="true" />

              <el-table-column label="库存数量" align="center" :show-overflow-tooltip="true">
                <template #default="scope">
                  <el-form-item label-width="0" :prop="'tableData.' + scope.$index + '.checkCount'"
                    :rules="{ required: true, message: '请选择产品通用名', trigger: 'blur'}">
                    <el-input v-model.number="scope.row.checkCount" placeholder="请输入库存数量">
                      <template #append>
                        {{ getLabel('sell_unit',scope.row?.product?.sellUnit) }}
                      </template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button type="text" @click="handlAdd(scope)">编辑</el-button>
                  <el-button type="text" @click="handlDelete(scope.$index,2)">删除</el-button>
                </template>
              </el-table-column>
            </table-view>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>

        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, inject, onMounted, reactive, toRefs,} from "vue";

export default {
  name: "RuleForm",
  setup(props, context) {
    const validateTable = (rule, value, callback) => {
      if (data.openForm.tableData.length === 0) {
        callback(new Error("至少添加一条数据"));
      } else {
        callback();
      }
    };
    const api = inject("api");
    const currentInstance = getCurrentInstance();
    const data = reactive({
      openBoole: false,
      openForm: {
        distributeName: "",
        distributeId: 0,
        checkTime: "",
        tableData: [],
        id: -1,
      },
      rules: {
        distributeName: [
          { required: true, message: "请选择配送商", trigger: "change" },
        ],
        checkTime: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
        tableData: [
          { required: true, validator: validateTable, trigger: "blur" },
        ],
      },
      openRef: null,
      productList: [],
      editType: 1,
      autocomplete:null
    });

    const querySearchAsync = async (queryString, cb) => {
      let results = [];
      const res = await api.terminal.PRODUCT_PULLLIST(queryString);
      if (res.code === 0) {
        results = res.data.list || [];
      }
      cb(results);
    };

    const handleSelect = (val) => {
      if (val) {
        data.openForm.distributeName = val.distributeName;
        data.openForm.distributeId = val.id;
        handlProduct(val.id);
      }
      handlDelete(null, 1);
    };

    const handleClear = ()=>{
        data.autocomplete.activated  = true
    }

    const handlProduct = (id) => {
      api.inventory.INVENTORY_PRODUCT(id).then((res) => {
        if (res.code === 0) {
          data.productList = res.data || [];
        }
      });
    };

    const handlRddtype = (id, index) => {
      const a = data.productList.find((b) => b.id === id);
      const b = {
        product: a,
        productId: id,
        checkCount: "",
      };
      var indexId = data.openForm.tableData.findIndex(
        (x) => x.productId === id
      );
      if (indexId !== index && indexId !== -1) {
        currentInstance.proxy.customMessage({
          type: "error",
          message: "产品重复",
        });
        data.openForm.tableData[index].productId = undefined;
      } else {
        data.openForm.tableData[index] = b;
      }
    };

    const handlDate = (val) => {
      const date = new Date(val);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      return `${year}年${month}月`;
    };

    const close = () => {
      data.openForm = {
        distributeName: "",
        distributeId: undefined,
        checkTime: "",
        tableData: [],
      };
      data.openBoole = false;
    };

    const open = (row) => {
      if (row) {
        console.log(row);
        data.openForm.distributeName = row?.distribute?.distributeName;
        data.openForm.distributeId = row?.distribute?.id;
        data.openForm.checkTime = row?.checkTime;
        data.openForm.tableData = row?.checkProductDetails;
        data.openForm.id = row?.id;
        handlProduct(row?.distribute?.id);
      }
      data.openBoole = true;
    };

    const handlAdd = (val) => {
      if (val === null) {
        data.openForm.tableData.push({ productId: undefined, checkCount: "" });
      } else {
        data.index = val.$index;
      }
    };

    const handlDelete = (index, num) => {
      if (num === 2) {
        data.openForm.tableData.splice(index, 1);
      }
      if (num === 1) {
        data.openForm.tableData = [];
      }
    };

    const handlSubmit = () => {
      console.log(data.openForm);
      data.openRef.validate((valid) => {
        if (valid) {
          var obj = {
            distributeId: data.openForm.distributeId,
            checkTime: data.openForm.checkTime,
            checkProductDetails: data.openForm.tableData.map((a) => {
              return {
                productId: a.productId,
                checkCount: a.checkCount,
              };
            }),
          };
          var obj1 = {
            distributeId: data.openForm.distributeId,
            checkTime: data.openForm.checkTime,
            checkProductDetails: data.openForm.tableData.map((a) => {
              return {
                productId: a.productId,
                checkCount: a.checkCount,
              };
            }),
            id: data.openForm.id,
          };
          var commit = undefined;
          var msgs = "";
          var dataObj = null;
          if (data.openForm.id === -1) {
            commit = api.inventory.INVENTORY_CREATE;
            msgs = "提交成功";
            dataObj = obj;
          }
          if (data.openForm.id > -1) {
            commit = api.inventory.INVENTORY_EDITER;
            msgs = "编辑成功";
            dataObj = obj1;
          }
          commit(dataObj).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: msgs,
              });
              context.emit("succsess");
              close();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    onMounted(() => {});
    return {
      ...toRefs(data),
      close,
      open,
      handlAdd,
      handlDelete,
      handlSubmit,
      querySearchAsync,
      handleSelect,
      handlDate,
      handlRddtype,
      handleClear
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
:deep(.tableForm .el-form-item--small.el-form-item) {
  margin-bottom: 0 !important;
}
</style>
